import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import api from '@/utils/api'
import { ElMessage } from 'element-plus'

export const useAuthStore = defineStore('auth', () => {
  const user = ref(null)
  const token = ref(localStorage.getItem('token') || null)
  const refreshToken = ref(localStorage.getItem('refreshToken') || null)

  const isAuthenticated = computed(() => !!token.value)
  const isAdmin = computed(() => user.value?.is_staff || false)

  // 登录
  const login = async (credentials) => {
    try {
      const response = await api.post('/users/login/', credentials)
      const { access, refresh, user: userData } = response.data
      
      token.value = access
      refreshToken.value = refresh
      user.value = userData
      
      localStorage.setItem('token', access)
      localStorage.setItem('refreshToken', refresh)
      
      // 设置默认请求头
      api.defaults.headers.common['Authorization'] = `Bearer ${access}`
      
      ElMessage.success('登录成功')
      return response.data
    } catch (error) {
      ElMessage.error(error.response?.data?.detail || '登录失败')
      throw error
    }
  }

  // 注册
  const register = async (userData) => {
    try {
      const response = await api.post('/users/register/', userData)
      ElMessage.success('注册成功，请登录')
      return response.data
    } catch (error) {
      ElMessage.error(error.response?.data?.detail || '注册失败')
      throw error
    }
  }

  // 登出
  const logout = () => {
    token.value = null
    refreshToken.value = null
    user.value = null
    
    localStorage.removeItem('token')
    localStorage.removeItem('refreshToken')
    
    delete api.defaults.headers.common['Authorization']
    
    ElMessage.success('已退出登录')
  }

  // 获取用户信息
  const fetchUser = async () => {
    try {
      const response = await api.get('/users/profile/')
      user.value = response.data
      return response.data
    } catch (error) {
      logout()
      throw error
    }
  }

  // 检查认证状态
  const checkAuth = async () => {
    if (token.value) {
      api.defaults.headers.common['Authorization'] = `Bearer ${token.value}`
      try {
        await fetchUser()
      } catch (error) {
        logout()
      }
    }
  }

  // 更新用户信息
  const updateProfile = async (data) => {
    try {
      const response = await api.patch('/users/profile/', data)
      user.value = response.data
      ElMessage.success('更新成功')
      return response.data
    } catch (error) {
      ElMessage.error(error.response?.data?.detail || '更新失败')
      throw error
    }
  }

  // 重置密码
  const resetPassword = async (email) => {
    try {
      const response = await api.post('/users/password-reset/', { email })
      ElMessage.success('重置邮件已发送')
      return response.data
    } catch (error) {
      ElMessage.error(error.response?.data?.detail || '发送失败')
      throw error
    }
  }

  return {
    user,
    token,
    refreshToken,
    isAuthenticated,
    isAdmin,
    login,
    register,
    logout,
    fetchUser,
    checkAuth,
    updateProfile,
    resetPassword
  }
})
